import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter_module/base/model/constants.dart';
import 'package:flutter_module/bloc/event/second_event.dart';
import 'package:flutter_module/bloc/second_bloc.dart';
import 'package:flutter_module/bloc/state/second_state.dart';
import 'package:flutter_module/model/article.dart';
import 'package:flutter_module/model/article_tags.dart';
import 'package:flutter_module/pages/mine/mine_page.dart';
import 'package:flutter_module/router/routers.dart';
import 'package:flutter_module/util/app_colors.dart';
import 'package:flutter_module/widget/custom_refresher.dart';
import 'package:flutter_module/widget/empty_view.dart';
import 'package:flutter_module/widget/error_view.dart';
import 'package:flutter_module/widget/init_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class PageList extends StatefulWidget {
  const PageList({super.key});

  @override
  State<PageList> createState() => _PageList();
}

class _PageList extends State<PageList> {
  late RefreshController _refreshController;

  /// CustomScrollView的控制器
  late ScrollController? _scrollController;

  /// 控制回到顶部按钮是否显示
  bool _isShowTop = false;

  @override
  void initState() {
    super.initState();
    // 创建刷新数据插件的控制器
    _refreshController = RefreshController();
    // 创建CustomScrollView的控制器
    _scrollController = ScrollController();
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
    _scrollController?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<SecondBloc, SecondState>(
      builder: (context, state) {
        return Scaffold(
            extendBodyBehindAppBar: true,//用来指定 Scaffold 的 appBar 是否应该被扩展到状态栏后面
            appBar: AppBar(
              toolbarHeight: 0,
              backgroundColor: Theme.of(context).scaffoldBackgroundColor,//状态栏的背景颜色
              systemOverlayStyle: SystemUiOverlayStyle.light,
            ),
            body: SafeArea(//沉浸式状态栏下的安全区域，使用SafeArea
              child: NotificationListener(
                onNotification: (ScrollNotification scrollNotification) {
                  // 监听滚动组件是否滚动结束
                  // scrollNotification.depth == 0 这里是下级的索引，就是指定监听哪个child的滚动位置
                  // scrollNotification is ScrollEndNotification:表示当前首页的CustomScrollView滚动结束了
                  if (scrollNotification.depth == 0 &&
                      scrollNotification is ScrollEndNotification) {
                    // 获取滚动的距离
                    debugPrint(
                        'scroll end ${scrollNotification.metrics.pixels}');
                    // 根据滚动距离显示或隐藏回到顶部按钮：如果滚动距离超过一屏，就显示回到顶部按钮
                    if (scrollNotification.metrics.pixels >=
                        MediaQuery.of(context).size.height) {
                      // 显示
                      _isShowTop = true;
                    } else {
                      // 隐藏
                      _isShowTop = false;
                    }
                    // 刷新状态
                    setState(() {});
                  }
                  return true; // 通知不再继续冒泡，不再继续下发通知
                },
                child: Stack(
                  children: [
                    CustomRefresher(
                      controller: _refreshController,
                      enablePullUp: true,
                      onRefresh: _loadData,
                      onLoading: _loadMore,
                      child: buildCustomScrollView(state),
                    ),
                    // Positioned可以定位回到顶部按钮
                    _isShowTop
                        ? Positioned(
                            right: 30.0,
                            bottom: 100.0,
                            child: ClipOval(
                              child: GestureDetector(
                                onTap: () {
                                  // 回到顶部逻辑
                                  _scrollController!.animateTo(
                                    0.0,
                                    duration: Duration(milliseconds: 400),
                                    curve: Curves.ease,
                                  );
                                },
                                child: Container(
                                  width: 46.0,
                                  height: 46.0,
                                  color: Colors.black12,
                                  child: Icon(Icons.arrow_upward),
                                ),
                              ),
                            ),
                          )
                        : Container(),
                  ],
                ),
              ),
            ));

        // return EasyRefresh(//暂不使用，更换
        //   header: const PhoenixHeader(),
        //   footer: const PhoenixFooter(),
        //   onRefresh: () async {
        //     await Future.delayed(const Duration(seconds: 1), () {
        //       _onRefresh();
        //     });
        //   },
        //   onLoad: () async {
        //     await Future.delayed(const Duration(seconds: 1), () async {
        //       LogU.log("下载加载更多 onLoad");
        //       _loadMore();
        //     });
        //   },
        //   child: buildCustomScrollView(state),
        // );
      },
    );
  }

  Widget buildCustomScrollView(SecondState state) {
    switch (state.status) {
      case PostStatus.failure:
        return ErrorView();
      case PostStatus.success:
        if (state.datas.isEmpty) {
          return EmptyView(); //空布局，列表为空
        }
        return CustomScrollView(
          controller: _scrollController,
          slivers: [
            SliverList(
              delegate: SliverChildBuilderDelegate((context, index) {
                return GestureDetector(
                  onTap: () => openH5Detail(index, state.datas[index]),
                  // onTap: openH5Detail(index),//错误写法，会导致openH5Detail方法没有被点击就执行了
                  child: buildItem(index, state.datas),
                );
              }, childCount: state.datas.length),
            ),
          ],
        );
      case PostStatus.initial:
        return InitView(); //骨架屏或其它
    }
  }

  Widget buildItem(int index, List<Article<ArticleTags>> datas) {
    var article = datas[index];

    print("article ------> $article");

    if (article.envelopePic.isEmpty) {
      return Container(
        margin: EdgeInsets.symmetric(vertical: 5.w, horizontal: 5.h),
        padding: EdgeInsets.symmetric(vertical: 5.w, horizontal: 5.h),
        decoration: BoxDecoration(boxShadow: [
          //卡片阴影
          BoxShadow(
            color: Colors.white,
            // offset: Offset(0, 0),
            blurRadius: 5.w,
          )
        ]),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Flex(
              direction: Axis.horizontal,
              children: [
                Text("新",
                    style: TextStyle(
                        fontSize: 14.sp, color: AppColors.color_6c1bc)),
                Expanded(
                    flex: 1,
                    child: Text(article.chapterName,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 14.sp, color: AppColors.color_7c7b7b))),
                Text(article.niceDate,
                    style: TextStyle(
                        fontSize: 12.sp, color: AppColors.color_999999))
              ],
            ),
            Text(article.title,
                textAlign: TextAlign.left,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style:
                    TextStyle(fontSize: 14.sp, color: AppColors.color_000000)),
            Flex(
              direction: Axis.horizontal,
              children: [
                Expanded(
                    flex: 1,
                    child: Text(article.author,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 12.sp, color: AppColors.color_999999))),
                Image.asset(
                  "assets/images/icon_collected.png",
                  width: 16.w,
                ),
              ],
            )
          ],
        ),
      );
    } else {
      return Container(
        margin: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
        padding: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
        decoration: BoxDecoration(boxShadow: [
          //卡片阴影
          BoxShadow(
            color: Colors.white,
            // offset: Offset(0, 0),
            blurRadius: 5,
          )
        ]),
        child: Flex(
          direction: Axis.horizontal,
          children: [
            // _buildImageWidget(article.envelopePic),
            _buildImageWidget(
                "https://wbedu.sanyaedu.org/res/20240904/png/1ddad595-9094-4c74-9a20-e37ccfbb691d.png"),
            Expanded(
                flex: 1,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Flex(
                      direction: Axis.horizontal,
                      children: [
                        Text("新",
                            style: TextStyle(
                                fontSize: 14, color: AppColors.color_6c1bc)),
                        Expanded(
                            flex: 1,
                            child: Text(article.chapterName,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 14,
                                    color: AppColors.color_7c7b7b))),
                        Text(article.niceDate,
                            style: TextStyle(
                                fontSize: 12, color: AppColors.color_999999))
                      ],
                    ),
                    Text(article.title,
                        textAlign: TextAlign.left,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 14, color: AppColors.color_000000)),
                    Flex(
                      direction: Axis.horizontal,
                      children: [
                        Expanded(
                            flex: 1,
                            child: Text(article.author,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 12,
                                    color: AppColors.color_999999))),
                        Image.asset(
                          "assets/images/icon_collected.png",
                          width: 16,
                        )
                      ],
                    )
                  ],
                ))
          ],
        ),
      );
    }
  }

  Widget _buildImageWidget(url) {
    return Image.network(
      url,
      height: 120.h,
      width: 75.w,
    );
  }

  openH5Detail(int index, Article<ArticleTags> article) {
    ///flutter页面跳转flutter页面
    BoostNavigator.instance
        .push(RouteGet.web, arguments: {Constants.url: article.link});
  }

  void _loadData() {
    //context.read(): 用于获取 Bloc 或 Cubit 的实例，但不监听变化。常用于触发动作（如按钮点击）时。这里是请求列表数据
    context.read<SecondBloc>().add(RefreshEvent());
    // 获取网络数据成功时:刷新结束
    _refreshController.refreshCompleted();
  }

  void _loadMore() {
    context.read<SecondBloc>().add(LoadMoreEvent());
    _refreshController.loadComplete();
  }
}
